<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>中断promise链</title>
  </head>
  <body>
    <!--
         中断promise链：
          （1）当使用promise的then链式调用时，在中间中断，不再调用后面的回调函数
          （2）办法： 在失败的问题回调函数中返回一个pending状态的Promise实例
     -->
    <script>
      function sendAjax(url, data) {
        return new Promise((resolve, reject) => {
          // 实例xhr
          const xhr = new XMLHttpRequest()
          // 绑定监听
          let str = ''
          for (let key in data) {
            str += `${key}=${data[key]}&`
          }
          str = str.slice(0, -1)

          xhr.open('GET', url + '?' + str)
          xhr.responseType = 'json'
          xhr.send()

          xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response)
              } else {
                reject('error!!!')
              }
            }
          }
        })
      }

      sendAjax('https://api.apiopen.top/api/getShortVideo?', { page: 0, size: 10 })
        .then(
          (value) => {
            console.log('第一次请求成功', value)
            return sendAjax('https://ap3i.apiopen.top/api/getShortVideo?', { page: 1 }) ≈
          },
          (reason) => {
            console.log('第一次请求失败', reason)
            return new Promise((resolve, reject) => {})
          }
        )
        .then(
          (value) => {
            console.log('第二次请求成功', value)
            return sendAjax('https://api.apiopen.top/api/getShortVideo?', { page: 2 })
          },
          (reason) => {
            console.log('第二次请求失败', reason)
            return new Promise((resolve, reject) => {}) //中断
          }
        )
        .then(
          (value) => {
            console.log('第三次请求成功', value)
          },
          (reason) => {
            console.log('第三次请求失败', reason)
          }
        )
    </script>
  </body>
</html>
